#include "command.h"

int _ln(char *argv[])
{
	/* check the number of cmd-line parameters is correct */
	int argc = 0;
	for (char **ptr = argv; *ptr != NULL; ptr++)
		argc++;

	if (argc < 3 || argc > 4) {
		fprintf(stderr, "Usage: ln [-s] src_path link_path\n");
		return -1;
	}

	int opt;
	const char *optfmt = "s";
	int symbolic_link = 0; 
	while ((opt = getopt(argc, argv, optfmt)) != -1) {
		switch (opt) {
			case 's':
				symbolic_link = 1;
				break;
			default:
				fprintf(stderr, "ln error: unknown option %c\n", opt);
				return -1;
		}
	}

	const char *src = argv[optind];
	const char *target = argv[optind + 1];

	if (!src || !target) {
		fprintf(stderr, "Usage: ln [-s] src_path link_path\n");
		return -1;
	}

	if (access(target, F_OK) == 0) {
		fprintf(stderr, "ln error: %s already exist\n", target);
		return -1;
	}

	if (symbolic_link == 1) {
		if (symlink(src, target) == -1) {
			fprintf(stderr, "ln error: symlink\n");
			return -1;
	 	}
	} else {
		if (link(src, target) == -1) {
			fprintf(stderr, "ln error: link\n");
			return -1;
	 	}
	}

	return 0;
}
